import React, {useState} from "react";
import { Space,Card, Table, Tag, Popconfirm, Form, InputNumber, Input,message } from "antd";
import { ConferenceContainer } from './style';
import ProConference from "./components/ProConference";
import { connect } from "react-redux";
import * as actionTypes from '../../store/actionCreators'
import {IDefaultState} from '../../global/globalInterFace';



interface IProps {
    dataSource: [],
    deleteItemDispatch(index: number): void,
    deleteItemBatch(indexArr: number[]): void,
    editItemBatch(key: number, newUserInfo: any): void,
}


interface IRowSelection {
    selectedRowKeys: number[],
    onChange: any,
}

function Conference(props:IProps) {
    // 选中数组下标
    let [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
    // 编辑下标
    const [editingKey, setEditingKey] = useState<string>('');
    // 删除下标数组
    let [deleteArr, setDeleteArr] = useState<number[]>([]);
    // props数据
    const { dataSource } = props;
    // props事件
    const {
        deleteItemDispatch,
        deleteItemBatch,
        editItemBatch
    } = props;
    // 配置第一行
    const columns = [
        {
            title: 'Number',
            dataIndex: 'Number',
            editable: true,
            sorter: {
                compare: (a: any, b: any) => a.Number - b.Number,
                multiple: 2
            }
        },
        {
            title: 'Name',
            dataIndex: 'Name',
            editable: true,
            sorter: {
                compare: (a: any, b: any) => {
                    return a.Name.length - b.Name.length
                },
                multiple: 1
            }
        },
        {
            title: 'Moderators',
            dataIndex: 'Moderators',
            // 定制
            render: (Arr: any) => {
                return Arr.map((num: any) => (
                    <Tag key={num}>
                        {num}
                    </Tag>
                ))
            }
        },
        {
            title: 'Operations',
            dataIndex: 'Operations',
            // 定制
            render: (text: any, record: any) => {
                const editable: boolean = isEditing(record);
                return editable === true ? isEdit(record) : isNotEdit(record);
            },
        },
    ];
    // 第一行增加可编辑
    const mergedColumns = columns.map((col: any) => {
        // 不可编辑的列
        if (!col.editable) {
            return col;
        }
        // 可编辑的列
        return {
            ...col,
            onCell: (record: any) => {
                return {
                    record,
                    inputType: col.dataIndex,
                    dataIndex: col.dataIndex,
                    editing: isEditing(record),
                }
            },
        };
    });
    // 可编辑的单元格
    const EditableCell = ({
                              editing,
                              dataIndex,
                              inputType,
                              record,
                              children,
                              ...restProps
                          }: any) => {

        let inputNode = undefined;
        switch (inputType) {
            case 'Number':
                inputNode = <Form.Item
                    key={dataIndex}
                    name={dataIndex}
                    style={{
                        margin: 0
                    }}
                    rules={[
                        {
                            required: true,
                            message: `Please Input ${dataIndex}!`,
                        },
                    ]}
                >
                    <InputNumber/>
                </Form.Item>;

                break;
            case 'Name':
                inputNode = <Form.Item
                    key={dataIndex}
                    name={dataIndex}
                    style={{
                        margin: 0
                    }}
                    rules={[
                        {
                            required: true,
                            message: `Please Input ${dataIndex}!`,
                        },
                    ]}
                >
                    <Input/>
                </Form.Item>;
                break;
            default:
                break;
        }
        return (
            <td {...restProps}>
                {editing ?
                    (inputNode)
                    : (
                        // 原来的样式
                        children
                    )
                }
            </td>
        );
    };
    // 编辑
    const clickEdit = (record: any) => {
        form.setFieldsValue({
            Number: '',
            Name: '',
            ...record,
        });
        setEditingKey(record.key);
    };
    const clickSave = (record: any) => {
        const formData = form.getFieldValue();
        const {
            key,
            Name,
            Number
        } = formData;

        if (!Name || Number === null) {
            message.info('Number或者Name不许为空');
            return;
        }
        const newObj = {
            key,
            Name,
            Number,
            Moderators: record.Moderators
        };
        editItemBatch(key,newObj);
        setEditingKey('');
    };
    // 是否编辑:
    const isEditing = (record: any) => record.key === editingKey;
    // 编辑状态
    const isEdit = (record: any) => {
        return (
            <Space size='middle'>
                <a  onClick={() => clickSave(record)}>Save</a>
                <Popconfirm title='确定取消?'  onConfirm={() => setEditingKey('')}>
                    <a >Cancel</a>
                </Popconfirm>
            </Space>
        )
    };
    // 不是编辑状态
    const isNotEdit = (record: any) => {
        return (
            <Space size='middle'>
                <a  onClick={() => clickEdit(record)}>Edit</a>
                <Popconfirm title='确定删除?'  onConfirm={() => deleteItem(record.key)}>
                    <a >Delete</a>
                </Popconfirm>
            </Space>
        )
    };
    // 多选装状态
    const onSelectChange = (selectedRowKeys: number[], selectedRows: any) => {
        setSelectedRowKeys(selectedRowKeys);
        let temp: number[] = [];
        // 找下标
        selectedRows.forEach((item: any) => {
         const index: number = dataSource.findIndex((subItem: any) => item.Name === subItem.Name);
            temp.push(index);
        });
        setDeleteArr(temp);
    };
    // 表格行是否可选择
    const rowSelection: IRowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    // form事件
    const [form]: any = Form.useForm();
    // 单个删除
    const deleteItem = (key: number) => {
        const index: number =  dataSource.findIndex(((item: any) => {
            return key === item.key;
        }));
        deleteItemDispatch(index);
    };
    // 允许批量删除
    const deleteStatus: boolean = selectedRowKeys.length > 0;
    // 批量删除
    const deleteBatch = () => {
        console.log(selectedRowKeys);
        deleteItemBatch(deleteArr);
        setSelectedRowKeys([]);
        setDeleteArr([]);
    };
    return(
        <ConferenceContainer>
            <div className="content">
                <Card>
                    <ProConference
                        deleteStatus={deleteStatus}
                        deleteBatch={deleteBatch}
                    />
                    <Form
                        form={form}
                        component={false}
                    >
                        <Table
                            components={{
                                body: {
                                    cell: EditableCell,
                                },
                            }}
                            bordered
                            columns={mergedColumns}
                            rowSelection={rowSelection}
                            dataSource={dataSource}
                            pagination={{defaultPageSize: 5}}
                        />
                    </Form>
                </Card>
            </div>

        </ConferenceContainer>
    )
}
const mapStateToProps = (state: IDefaultState) => {
    return {
        dataSource: state.dataSource
    }
};
// 第三方建议使用any
const mapDispatchToProps = (dispatch: any) => {
    return{
        deleteItemDispatch(index: number){
            dispatch(
                actionTypes.deleteItem(index)
            )
        },
        deleteItemBatch(indexArr: number[]){
            dispatch(
                actionTypes.deleteBatch(indexArr)
            )
        },
        editItemBatch(index:number, obj: any){
            dispatch(
                actionTypes.editItem(index, obj)
            )
        }
    }
};

export default connect (mapStateToProps, mapDispatchToProps)(React.memo (Conference));

